package com.cj.minio.service.impl;

import com.cj.minio.config.MinioConfig;
import com.cj.minio.entity.FileInfo;
import com.cj.minio.service.FileInfoService;
import com.cj.minio.service.MinioService;
import com.cj.minio.util.file.FileTypeUtils;
import io.minio.*;
import io.minio.http.Method;
import io.minio.messages.Bucket;
import io.minio.messages.Item;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * minio服务
 *
 * @author Mjg
 * @QQ:2091864671
 * @Create by mjg ON 2021/5/21-16:30
 * @date 2021/05/21
 */
@Slf4j
@Service
public class MinioServiceImpl implements MinioService {
    @Resource
    private MinioConfig minioConfig;
    @Resource
    private MinioClient minioClient;
    @Resource
    private FileInfoService fileInfoService;

    @Override
    public String upload(MultipartFile file) {
        String fileType = FileTypeUtils.getFileType(file.getOriginalFilename());
        log.info("fileType --- {}", fileType);

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String format = formatter.format(LocalDateTime.now());
        String fileName = format + "/" + file.getOriginalFilename();
        String url = null;
        try {
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .object(fileName)
                    .bucket(minioConfig.getBucketName())
                    .contentType(file.getContentType())
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .build();
            minioClient.putObject(putObjectArgs);
            url = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
                    .method(Method.GET)
                    .bucket(minioConfig.getBucketName())
                    .object(fileName)
                    .build());
//        FileInfo fileInfo = FileInfo.builder()
//                .fileName(file.getOriginalFilename())
//                .fileUrl(url)
//                .size(file.getSize())
//                .build();
//        fileInfoService.save(fileInfo);
        } catch (Exception e) {
        }
        return url;
    }



    /**
     * 删除一个对象
     *
     * @param bucketName 存储桶名称
     * @param objectName 存储桶里的对象名称
     */
    @SneakyThrows
    @Override
    public boolean removeObject(String bucketName, String objectName) {
        boolean flag = bucketExists(bucketName);
        if (flag) {
            minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(objectName).build());
            return true;
        }
        return false;
    }

    /**
     * @description: 获取上传文件的url
     * @dateTime: 2021/5/13 14:15
     */
    @SneakyThrows
    @Override
    public String getPolicyUrl(String objectName, int time, TimeUnit timeUnit) {
        // objectName是完整路径(2021-09-20/333.jpg)
        return minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
                .method(Method.GET)
                .bucket(minioConfig.getBucketName())
                .object(objectName)
                .expiry(time, timeUnit).build());
    }


    /**
     * 检查存储桶是否存在
     *
     * @param bucketName 存储桶名称
     * @return
     */
    @SneakyThrows
    @Override
    public boolean bucketExists(String bucketName) {
        return minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
    }

    /**
     * 创建存储桶
     *
     * @param bucketName 存储桶名称
     */
    @SneakyThrows
    @Override
    public boolean makeBucket(String bucketName) {
        boolean flag = bucketExists(bucketName);
        if (!flag) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            String policy = "{\n" +
                    "\t\"Version\": \"2012-10-17\",\n" +
                    "\t\"Statement\": [{\n" +
                    "\t\t\"Effect\": \"Allow\",\n" +
                    "\t\t\"Principal\": {\n" +
                    "\t\t\t\"AWS\": [\"*\"]\n" +
                    "\t\t},\n" +
                    "\t\t\"Action\": [\"s3:GetBucketLocation\", \"s3:ListBucket\", \"s3:ListBucketMultipartUploads\"],\n" +
                    "\t\t\"Resource\": [\"arn:aws:s3:::" + bucketName + "\"]\n" +
                    "\t}, {\n" +
                    "\t\t\"Effect\": \"Allow\",\n" +
                    "\t\t\"Principal\": {\n" +
                    "\t\t\t\"AWS\": [\"*\"]\n" +
                    "\t\t},\n" +
                    "\t\t\"Action\": [\"s3:AbortMultipartUpload\", \"s3:DeleteObject\", \"s3:GetObject\", \"s3:ListMultipartUploadParts\", \"s3:PutObject\"],\n" +
                    "\t\t\"Resource\": [\"arn:aws:s3:::" + bucketName + "/*\"]\n" +
                    "\t}]\n" +
                    "}\n";
            minioClient.setBucketPolicy(SetBucketPolicyArgs
                    .builder()
                    .bucket(bucketName)
                    .config(policy)
                    .build());

            return true;
        }
        return false;
    }


    /**
     * 列出所有存储桶
     *
     * @return
     */
    @SneakyThrows
    @Override
    public List<Bucket> listBuckets() {
        return minioClient.listBuckets();
    }

    /**
     * 列出所有存储桶名称
     *
     * @return
     */
    @SneakyThrows
    @Override
    public List<String> listBucketNames() {
        List<Bucket> bucketList = listBuckets();
        List<String> bucketListName = new ArrayList<>();
        for (Bucket bucket : bucketList) {
            bucketListName.add(bucket.name());
        }
        return bucketListName;
    }

    /**
     * 列出存储桶中的所有对象
     *
     * @param bucketName 存储桶名称
     * @return
     */
    @SneakyThrows
    @Override
    public Iterable<Result<Item>> listObjects(String bucketName) {
        boolean flag = bucketExists(bucketName);
        if (flag) {
            return minioClient.listObjects(ListObjectsArgs.builder().bucket(bucketName).build());
        }
        return null;
    }

    /**
     * 列出存储桶中的所有对象名称
     *
     * @param bucketName 存储桶名称
     * @return
     */
    @SneakyThrows
    @Override
    public List<String> listObjectNames(String bucketName) {
        List<String> listObjectNames = new ArrayList<>();
        boolean flag = bucketExists(bucketName);
        if (flag) {
            Iterable<Result<Item>> myObjects = listObjects(bucketName);
            for (Result<Item> result : myObjects) {
                Item item = result.get();
                System.out.println(item.size());
                System.out.println(item.lastModified());
                listObjectNames.add(item.objectName());
            }
        }
        return listObjectNames;
    }


}
